/*
 * BadgeView.java
 * BadgeView
 *
 * Copyright (c) 2012 Stefan Jauker.
 * https://github.com/kodex83/BadgeView
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jauker.widget;

import ohos.agp.colors.RgbColor;
import ohos.agp.colors.RgbPalette;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.text.Font;
import ohos.agp.utils.Color;
import ohos.agp.utils.TextAlignment;
import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;

import java.util.Optional;

public class BadgeView extends Text {
    public static final String COLOR_RED = "#d3321b";
    private Context mContext;
    private boolean mHideOnNull = true;

    public BadgeView(Context context) {
        this(context, null);
        mContext = context;
    }

    public BadgeView(Context context, AttrSet attrs) {
        this(context, attrs, null);
        mContext = context;//changed
    }

    public BadgeView(Context context, AttrSet attrs, String defStyle) {
        super(context, attrs, defStyle);
        mContext = context;
        init();
    }

    private void init() {
        if (!(getLayoutConfig() instanceof StackLayout.LayoutConfig)) {
            StackLayout.LayoutConfig layoutParams =
                    (StackLayout.LayoutConfig) new StackLayout.LayoutConfig(
                            ComponentContainer.LayoutConfig.MATCH_CONTENT,
                            ComponentContainer.LayoutConfig.MATCH_CONTENT, TextAlignment.RIGHT | TextAlignment.TOP);

            setLayoutConfig(layoutParams);
        }
        setTextColor(Color.WHITE);
        setFont(Font.DEFAULT_BOLD);
        setTextSize(11, TextSizeType.VP);
        setPadding(dip2Px(5), dip2Px(1), dip2Px(5), dip2Px(1));
        setBackground(9, RgbPalette.parse(COLOR_RED));
        setTextAlignment(TextAlignment.CENTER);
        setHideOnNull(true);
        setBadgeCount(0);
    }

    public void setBackground(int dipRadius, int badgeColor) {
        int radius = dip2Px(dipRadius);
        float[] radiusArray = new float[]{radius, radius, radius, radius, radius, radius, radius, radius};
        ShapeElement bgDrawable = new ShapeElement();
        bgDrawable.setShape(ShapeElement.OVAL);
        bgDrawable.setCornerRadius(dipRadius);
        bgDrawable.setCornerRadiiArray(radiusArray);
        bgDrawable.setRgbColor(new RgbColor(badgeColor));
        setBackground(bgDrawable);
    }

    /**
     * isHideOnNull
     * @return Returns true if view is hidden on badge value 0 or null;
     */
    public boolean isHideOnNull() {
        return mHideOnNull;
    }

    /**
     * setHideOnNull
     * @return setHideOnNull the sethideonNull to return
     * @param hideOnNull the hideOnNull to set
     */
    public void setHideOnNull(boolean hideOnNull) {
        mHideOnNull = hideOnNull;
        setText(getText());
    }

    @Override
    public void setText(String text) {
        super.setText(text);
        if (isHideOnNull() && (text == null || text.toString().equalsIgnoreCase("0"))) {
            setVisibility(Component.INVISIBLE);
        } else {
            setVisibility(Component.VISIBLE);
        }
        super.setText(text);
    }

    public Integer getBadgeCount() {
        if (getText() == null) {
            return null;
        }

        String text = getText().toString();
        try {
            return Integer.parseInt(text);
        } catch (NumberFormatException e) {
            return null;
        }
    }

    public void setBadgeCount(int count) {

        setText(String.valueOf(count));
    }

    public int getBadgeGravity() {
        StackLayout.LayoutConfig params = (StackLayout.LayoutConfig) getLayoutConfig();
        return params.alignment;
    }

    public void setBadgeGravity(int gravity) {
        StackLayout.LayoutConfig params = (StackLayout.LayoutConfig) getLayoutConfig();
        params.alignment = gravity;
        setLayoutConfig(params);
    }

    public void setBadgeMargin(int leftDipMargin, int topDipMargin, int rightDipMargin, int bottomDipMargin) {
        StackLayout.LayoutConfig params = (StackLayout.LayoutConfig) getLayoutConfig();
        params.setMarginLeft(dip2Px(leftDipMargin));
        params.setMarginTop(dip2Px(topDipMargin));
        params.setMarginRight(dip2Px(rightDipMargin));
        params.setMarginBottom(dip2Px(bottomDipMargin));
        setLayoutConfig(params);
    }

    public int[] getBadgeMargin() {
        StackLayout.LayoutConfig params = (StackLayout.LayoutConfig) getLayoutConfig();
        return new int[]{params.getMarginLeft(), params.getMarginTop(), params.getMarginRight(), params.getMarginBottom()};
    }

    public void setBadgeMargin(int dipMargin) {
        setBadgeMargin(dipMargin, dipMargin, dipMargin, dipMargin);
    }

    public void incrementBadgeCount(int increment) {
        Integer count = getBadgeCount();
        if (count == null) {
            setBadgeCount(increment);
        } else {
            setBadgeCount(increment + count);
        }
    }

    public void decrementBadgeCount(int decrement) {
        incrementBadgeCount(-decrement);
    }

    /*
     * Attach the BadgeView to the TabWidget
     *
     * @param target the TabWidget to attach the BadgeView
     *
     * @param tabIndex index of the tab
     */
    public void setTargetView(PageSliderIndicator target, int tabIndex) {
        Component tabView = target.getPageSlider();
        setTargetView(tabView);
    }

    /*
     * Attach the BadgeView to the target view
     *
     * @param target the view to attach the BadgeView
     */
    public void setTargetView(Component target) {
        if (getComponentParent() != null) {
            ((ComponentContainer) getComponentParent()).removeComponent(this);
        }
        if (target == null) {
            return;
        }
        if (target.getComponentParent() instanceof StackLayout) {
            ((StackLayout) target.getComponentParent()).addComponent(this);
        } else if (target.getComponentParent() instanceof ComponentContainer) {
            ComponentContainer parentContainer = (ComponentContainer) target.getComponentParent();
            int groupIndex = parentContainer.getChildIndex(target);
            parentContainer.removeComponent(target);

            StackLayout badgeContainer = new StackLayout(getContext());
            ComponentContainer.LayoutConfig parentLayoutParams = target.getLayoutConfig();

            badgeContainer.setLayoutConfig(parentLayoutParams);
            target.setLayoutConfig(new ComponentContainer.LayoutConfig(
                    ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_PARENT));

            parentContainer.addComponent(badgeContainer, groupIndex, parentLayoutParams);
            badgeContainer.addComponent(target);
            badgeContainer.addComponent(this);
        }

    }

    /*
     * converts dip to px
     */
    private int dip2Px(float dip) {
        Optional<Display> optionalDisplay = DisplayManager.getInstance().getDefaultDisplay(mContext);
        Display display = null;
        float density = 0;
        if (optionalDisplay.isPresent()) {
            display = optionalDisplay.get();
        }

        if (display != null && display.getAttributes() != null) {
            density = display.getAttributes().densityPixels;
        }
        if (density == 0) {
            return (int) dip;
        }
        return (int) (dip * density + 0.5f);
    }

}

